import {
  deleteChartUsingPost,
  getChartByIdUsingGet,
  listChartByPageUsingPost,
  updateChartUsingPost,
} from '@/services/pikimbi/chartController';
import { useModel } from '@@/exports';
import { FrownTwoTone, SmileOutlined } from '@ant-design/icons';
import {
  Avatar,
  Button,
  Card,
  Flex,
  Form,
  Input,
  List,
  message,
  Modal,
  Result,
  Select,
  Space,
  Typography,
} from 'antd';
import Search from 'antd/es/input/Search';
import TextArea from 'antd/es/input/TextArea';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { request } from './../app.tsx';

const { Title } = Typography;

const AllChart: React.FC = () => {
  const initSearchParams = {
    current: 1,
    pageSize: 4,
    sortField: 'createTime',
    sortOrder: 'desc',
  };

  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};

  const [chartData, setChartData] = useState<API.Chart | undefined>();

  const [chartList, setChartList] = useState<API.Chart[]>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(true);
  const { baseURL } = request;
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);

  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [currentChartId, setCurrentChartId] = useState<number>(0);
  const [submitting, setSubmitting] = useState<boolean>(false);

  const fetchChartData = async (chartId: number) => {
    if (!chartId || chartId <= 0) {
      throw new Error('无效的图表ID');
    }
    try {
      const res = await getChartByIdUsingGet({ id: chartId });
      if (res.data) {
        setChartData({ ...res.data });
        return res.data;
      } else {
        message.error(res.message);
      }
    } catch (error) {
      throw new Error(error instanceof Error ? error.message : '请求异常');
    }
  };

  const showModal = async (chartId: number) => {
    setCurrentChartId(chartId);
    try {
      const chartData = await fetchChartData(chartId);
      if (chartData) {
        form.setFieldsValue({
          chartName: chartData?.chartName,
          chartType: chartData?.chartType,
          goal: chartData?.goal,
          chartData: chartData?.dynamicData,
        });
        setIsModalOpen(true);
      }
    } catch (error) {
      message.error('获取图表数据失败', error.message);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
  };

  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listChartByPageUsingPost(searchParams);
      if (res.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
        if (res.data.records) {
          res.data.records.forEach((data) => {
            if (!res.data.records.genChart) {
              const chartOption = JSON.parse(data.genChart ?? '{}');
              chartOption.title = undefined;
              data.genChart = JSON.stringify(chartOption);
            }
          });
        }
      } else {
        message.error('获取我的图表失败: ' + res.message);
      }
    } catch (e: any) {
      message.error('获取我的图表失败,' + e.message);
    }
    setLoading(false);
  };

  const onFinish = async (values: any) => {
    if (submitting) {
      return;
    }
    setSubmitting(true);
    try {
      const res = await updateChartUsingPost({
        id: currentChartId,
        ...values,
      });
      if (res.data) {
        message.success('已重新生成');
        await loadData();
        setIsModalOpen(false);
      } else {
        message.error('重新生成失败，' + res.message);
      }
    } catch (e: any) {
      message.error('重新生成失败，' + e.message);
    }
    setSubmitting(false);
  };

  useEffect(() => {
    loadData();
  }, [searchParams]);

  const addChartClick = () => {
    navigate('/add_chartAsync');
  };

  const deleteChart = async (chartId: number) => {
    if (!chartId || chartId <= 0) {
      throw new Error('无效的图表ID');
    }
    try {
      const res = await deleteChartUsingPost({ id: chartId });
      if (res.data) {
        await loadData();
        return res.data;
      } else {
        await loadData();
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      message.error(error.message || '请求异常1');
    }
  };

  function showDeleteModal(id) {
    setCurrentChartId(id);
    setIsDeleteModalOpen(true);
  }

  const handleOkCancel = async () => {
    try {
      const data = await deleteChart(currentChartId);
      if (data) {
        message.success('删除图表成功');
      }
    } catch (error) {
      message.error(error.message || '请求异常');
    }
    setIsDeleteModalOpen(false);
  };

  const handleDeleteCancel = () => {
    setIsDeleteModalOpen(false);
  };

  return (
    <div className="my-chart-page">
      <div>
        <Search
          placeholder="请输入图表名称"
          enterButton
          loading={loading}
          onSearch={(value) => {
            setSearchParams({
              ...initSearchParams,
              name: value,
            });
          }}
        />
      </div>
      <div className={'margin-bottom-16'} />
      <List
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        itemLayout="vertical"
        size="large"
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              current: page,
              pageSize,
            });
          },
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total: total,
        }}
        loading={loading}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card style={{ width: '100%' }}>
              {/*<Title level={5} style={{color:'#1677FF','margin-left': '10%'}}>{item?.username}</Title>*/}
              <List.Item.Meta
                avatar={<Avatar src={baseURL + '/api/' + (item && item?.userAvatar)} />}
                title={item.username}
                description={item.chartType ? '图表类型：' + item.chartType : undefined}
              />
              <>
                {item.status === 'SUCCEED' && (
                  <>
                    <div className={'margin-bottom-16'} />
                    <p className={'margin-left-6'}>
                      {'分析目标：' + item.goal}
                      <>
                        <Button
                          type="primary"
                          onClick={() => showModal(item.id)}
                          style={{ float: 'right' }}
                        >
                          修改诉求
                        </Button>
                        <Modal
                          title="重新生成图表"
                          open={isModalOpen}
                          onCancel={handleCancel}
                          footer={null}
                          destroyOnClose
                        >
                          <Form
                            form={form}
                            name="regenerateChart"
                            labelAlign="left"
                            labelCol={{ span: 6 }}
                            wrapperCol={{ span: 18 }}
                            onFinish={onFinish}
                          >
                            <Form.Item
                              name="chartName"
                              label="图表名称"
                              rules={[{ required: true, message: '请输入图表名称!' }]}
                            >
                              <Input placeholder="请输入图表名称" />
                            </Form.Item>

                            <Form.Item
                              name="chartType"
                              label="图表类型"
                              rules={[{ required: true, message: '请选择图表类型!' }]}
                            >
                              <Select
                                options={[
                                  { value: '折线图', label: '折线图' },
                                  { value: '柱状图', label: '柱状图' },
                                  { value: '堆叠图', label: '堆叠图' },
                                  { value: '饼图', label: '饼图' },
                                ]}
                              />
                            </Form.Item>

                            <Form.Item
                              name="goal"
                              label="分析目标"
                              rules={[{ required: true, message: '请输入分析目标!' }]}
                            >
                              <TextArea rows={4} />
                            </Form.Item>

                            <Form.Item
                              name="chartData"
                              label="原始数据"
                              rules={[{ required: true, message: '请输入原始数据!' }]}
                            >
                              <TextArea rows={8} />
                            </Form.Item>

                            <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                              <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                <Button onClick={handleCancel}>取消</Button>
                                <Button
                                  type="primary"
                                  htmlType="submit"
                                  loading={submitting}
                                  disabled={submitting}
                                >
                                  重新生成
                                </Button>
                              </Space>
                            </Form.Item>
                          </Form>
                        </Modal>
                      </>
                    </p>
                    <p className={'margin-left-6'}>{'分析结果：' + item.genResult}</p>
                    <div className={'margin-bottom-100'} />
                    <ReactECharts option={item.genChart && JSON.parse(item.genChart)} />
                    <Flex gap="small" wrap style={{ float: 'right' }}>
                      <Button
                        color="danger"
                        variant="outlined"
                        onClick={() => showDeleteModal(item.id)}
                      >
                        删除图表
                      </Button>
                      <Modal
                        title="删除图表"
                        open={isDeleteModalOpen}
                        onOk={handleOkCancel}
                        onCancel={handleDeleteCancel}
                        okText="确认"
                        cancelText="取消"
                      >
                        <p style={{ 'margin-top': '26px' }}>确定要删除图表嘛 ？ </p>
                      </Modal>
                    </Flex>
                  </>
                )}
                {item.status === 'FAILDE' && (
                  <>
                    <Result
                      icon={<FrownTwoTone />}
                      title="图表生成失败，请重新生成"
                      extra={
                        <Button type="primary" onClick={addChartClick}>
                          重新生成
                        </Button>
                      }
                    />
                    <div style={{ 'margin-bottom': '36px' }} />
                  </>
                )}
                {item.status === 'RUNNING' && (
                  <>
                    <Result icon={<SmileOutlined />} title="图表正在生成...，请重等候" />
                  </>
                )}
                {item.status === 'WAIT' && (
                  <>
                    <Result icon={<SmileOutlined />} title="图表等待生成，请重等候" />
                  </>
                )}
              </>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};
export default AllChart;
